// 路由解析
app.controller('z-route-c', [ '$scope','$rootScope', '$route','$routeParams','$compile','$http','$location','z-user-s','ZModel','z-forgetPassword-s',
		function($scope,$rootScope, $route,$routeParams,$compile,$http,$location,UserService, ZModel, forgetPasswordService) {
////实现HTML5后再用
//$rootScope.$watch('$locationChangeSuccess',function(n,o) {
//	debugger;
//});
	var navModel = ZModel.getInstance().navModel;
	
	var search=$location.search()['key'];
	
	var pathNum = $location.search()['pathNum'];
	
	//bpm平台系统令牌
	var tokenKey="ACC9C-849F8-ADD2B-0A326-154FF";
	//获取单点登录请求参数
	var addressKey=$location.search()['address_key'];
	var tokenId=$location.search()['tokenId'];
	
	//验证是否存在KEY
	if(angular.isUndefined(search)
			&& angular.isUndefined(addressKey)){
		//不存在
		currentUser();
	}else if(angular.isUndefined(search)==false
				&& angular.isUndefined(addressKey)){
		//验证key是否使用, 调用方法验证KEY
		UserService.checkKey({
					key:search
				},
				function(data) {
					if(data==0){
						routing(false);
					}else if(data==1){
						routing(true);
						//跳转审批列表
						tipClick(pathNum);
					}else{
//						$rootScope.alertWarning("无效的链接地址！");
						$location.path("/login");
						$location.search("")
						$location.hash("");
						$location.replace();
					}
				},
				function() {});
	}else if(angular.isUndefined(addressKey)==false
				&& angular.isUndefined(search)){
		//验证是否正确BPM单点登录KEY
		if(addressKey==tokenKey){
			//请求方法验证单点登录
			UserService.getSingleSignOn({
						tokenId: tokenId
					},
					function(currentUser) {	
						$rootScope.currentUser = currentUser;
						routing(true);
					},
					function(error) {
						routing(false);
						$rootScope.alertError(error.fault.message);
					});
		}else{
			$location.path("/login");
			$location.search("")
			$location.hash("");
			$location.replace();
		}
	}
	
	//todo
	function tipClick(value){
		var url=null;
		/*
		 * if (requestType==7) {//加班
				pathNum = "ot";//overtime
			} else if (requestType==8) {//出差
				pathNum = "bt";//businessTrip
			} else if (requestType==9) {//外出
				pathNum = "go";//goOut
			} else if (requestType==99) {//补签申请
				pathNum = "rr";//retroactiveRequest
			} else {//其它申请
				pathNum = "or";//othersRequest
		 */
		if(value=="rr"){
			$location.path("/raApproval/raApprovalList");
			$location.search("")
			$location.hash("");
			$location.replace();
		}else if(value=="or"){
			$location.path("/requestApproval/requestApprovalList");
			$location.search("")
			$location.hash("");
			$location.replace();
		}else if(value=="ot"){
			$location.path("/workOvertimeApproval/workOvertimeApprovalList");
			$location.search("")
			$location.hash("");
			$location.replace();
		}else if(value=="bt"){
			$location.path("/businessTripApproval/businessTripApprovalList");
			$location.search("")
			$location.hash("");
			$location.replace();
		}else if(value=="go"){
			$location.path("/goOutApproval/goOutApprovalList");
			$location.search("")
			$location.hash("");
			$location.replace();
		}else if(value=="sr"){
			$location.path("/salaryApproval/salaryApprovalList");
			$location.search("")
			$location.hash("");
			$location.replace();
		}
	};
	//todo end

	function currentUser(){
		//已登陆过
		if($rootScope.currentUser) {
			routing(true);
		} else {
			if($route.current.$$route.title=="login") {
				routing(false);
			} else {
				UserService.getLoginUser(
					function(currentUser) {
						$rootScope.currentUser = currentUser;
						routing(true);
					},
					function() {
						routing(false);
					});
			}
		};
	};
	
	function routing(isLogined) {
		if(isLogined) {//代表已登录
			if($route.current.$$route.title=="login") {//访问登陆页
				//请求均会跳到else内
				//返回上一个页面，如果没有，则请求index
				if(navModel.beforeLoginUrl) {//从未登录转为登录的
					$location.path(navModel.beforeLoginUrl);
					$location.hash("");
					$location.replace();
				} else {//直接访问登陆页或已登录再访问登陆页
					if(navModel.prevPage) {
						$location.path(navModel.prevUrl);
						$location.hash("");
						$location.replace();
					} else {
						$location.path("/index");
						$location.hash("");
						$location.replace();
					}
				}
			} else if($route.current.$$route.title=="index") {
				//如果没有上一个页面或上一个页面是登陆页，加载主页面，如果有则改变currentPage
				if(!navModel.prevPage||navModel.prevPage == "login") {
					loadPage($route.current.$$route.url);
					navModel.prevPage = $route.current.$$route.title;
					navModel.prevUrl = $location.$$url;
					if(navModel.beforeLoginUrl) {
						$location.path(navModel.beforeLoginUrl);
						$location.hash("");
						$location.replace();
					} else {
						var location = {};
						angular.copy($routeParams,location);
						navModel.location = location;
					}
					
				} else {
					if(navModel.prevPage != "index") {
						loadPage($route.current.$$route.url);
					}
					navModel.location = $routeParams;
					navModel.prevPage = $route.current.$$route.title;
					navModel.prevUrl = $location.$$url;
				}
			} else {
				loadPage($route.current.$$route.url);
				navModel.location = $routeParams;
				navModel.prevPage = $route.current.$$route.title;
				navModel.prevUrl = $location.$$url;
			}
		} else {//代表没登录
			if($route.current.$$route.title=="login"){//访问登陆页
				//加载登陆页
				loadPage($route.current.$$route.url);
				navModel.prevPage = $route.current.$$route.title;
				navModel.prevUrl = $location.$$url;
			} else if($route.current.$$route.title=="index") {
				loadPage($route.current.$$route.url);
				navModel.prevPage = $route.current.$$route.title;
				navModel.prevUrl = $location.$$url;
				//记录作为要访问的页面，并跳转到登陆页
				//navModel.beforeLoginUrl = $location.$$url;
				$location.path("/login");
				$location.hash("");
				$location.replace();
			} else {
				loadPage($route.current.$$route.url);
				var location = {};
				angular.copy($routeParams,location);
				navModel.location = location;
				navModel.prevPage = $route.current.$$route.title;
				navModel.prevUrl = $location.$$url;
			}
		}
		
	};
	
	function loadPage(url) {
		$rootScope.loadUrl = url;
//		//跳转的规则与当前页面相同
//		$http.get(url).success(function(data, status, headers, config) {
//			$compile( angular.element(document).find('#routePage').html(data) )( $rootScope );
//		});
	};
}]);

// 导航控制器
app.controller("z-nav-c", [ '$scope','$rootScope', 'z-nav-s', '$location','$timeout','ZModel','tokenService','z-user-s',
		function(scope,$rootScope,NavService,$location,$timeout,ZModel,TokenService,UserService) {
			scope.menuData = [];//菜单树形数据源
			scope.allPages = [];//当前打开所有页数据源
			scope.navTab = {};//导航Tab引用
			scope.menuTree = {};//菜单树形引用
			scope.bindTokenData = function(){
				var tokenData = TokenService(0, false);//读取全局变量
				if(tokenData.token==0){
					//获取登陆用户信息
					UserService.getLoginUser(function(data) {
						TokenService(data.token, true); //设置全局变量
						scope.bindMenuData();
					},function() {});
				}else{
					scope.bindMenuData();
				}
			};
			
			scope.bindMenuData = function(){
				NavService.getMenuData(function(data){
					//菜单数据源
					scope.menuData = data;
//					if($rootScope.currentUser.privilegeGroupId==1) {//经理首页
//						scope.menuData.splice(0,0,{id:'index',label : "管理员首页",url : "home/manage",isHomePage:1});
//					} else if ($rootScope.currentUser.privilegeGroupId==3) {//财务首页
//						scope.menuData.splice(0,0,{id:'index',label : "财务首页",url : "home/statistics",isHomePage:1});
//					} else if ($rootScope.currentUser.privilegeGroupId==4) {//经理首页 按周工时录入
//						scope.menuData.splice(0,0,{id:'index',label : "工时录入（周）",url : "home/weekLabor",isHomePage:1});
//					} else {//默认 员工首页 按天工时录入
//						scope.menuData.splice(0,0,{id:'index',label : "工时录入（天）",url : "home/dayLabor",isHomePage:1});
//					}
					
					scope.menuMap = {};
					
					ZFrame.treeToList(scope.menuData,function(menu) {
						if(menu.url) {
							scope.menuMap[menu.url] = menu;
						}
						if(menu.isHomePage === 1||scope.menuData.length==1) {
							$timeout(function() {
								scope.currentPage = menu;
							});
						}
						
					});
					
					scope.onClick=function(){
						$location.path("/requestApproval/requestApprovalList");
						$location.hash("");
						$location.replace();
					};
					
					scope.tipClick=function(value){
						var url=null;
						if(value==1){
							var page={};
							page.id=35;
							page.pId=34;
							page.code="m_35";
							page.label="补签审批";
							page.url="raApproval/raApprovalList";
							page.alias="补签审批（审批用户）";
							page.isHomePage=null;
							page.icons="symbol";
							page.children=[];
							scope.currentPage = page;
							
							url="raApproval/raApprovalList";
							$location.path("/"+url); 
							$location.replace();
						}else if(value==2){
							var page={};
							page.id=36;
							page.pId=34;
							page.code="m_36";
							page.label="休假审批";
							page.url="requestApproval/requestApprovalList";
							page.alias="休假审批（审批用户）";
							page.isHomePage=null;
							page.icons="symbol";
							page.children=[];
							scope.currentPage = page;
							
							url="requestApproval/requestApprovalList";
							$location.path("/"+url);
							$location.replace();
						}else if(value==3){
							var page={};
							page.id=37;
							page.pId=34;
							page.code="m_37";
							page.label="加班审批";
							page.url="workOvertimeApproval/workOvertimeApprovalList";
							page.alias="加班申请（审批人）";
							page.isHomePage=null;
							page.icons="symbol";
							page.children=[];
							scope.currentPage = page;
							
							url="workOvertimeApproval/workOvertimeApprovalList";
							$location.path("/"+url);
							$location.replace();
						}else if(value==4){
							var page={};
							page.id=38;
							page.pId=34;
							page.code="m_38";
							page.label="出差审批";
							page.url="businessTripApproval/businessTripApprovalList";
							page.alias="出差审批（审批人）";
							page.isHomePage=null;
							page.icons="symbol";
							page.children=[];
							scope.currentPage = page;
							
							url="businessTripApproval/businessTripApprovalList";
							$location.path("/"+url);
							$location.replace();
						}else if(value==5){
							var page={};
							page.id=39;
							page.pId=34;
							page.code="m_39";
							page.label="外出审批";
							page.url="goOutApproval/goOutApprovalList";
							page.alias="外出审批（审批人）";
							page.isHomePage=null;
							page.icons="symbol";
							page.children=[];
							scope.currentPage = page;
							
							url="goOutApproval/goOutApprovalList";
							$location.path("/"+url);
							$location.replace();
						}
						//控制菜单显示
						ZFrame.eachTree(scope.menuData,function(node) {
							if(scope.menuMap[node.url]&&node.url == url) {
								scope.menuTree.toggle(node);
							}
						});
					};
					
					scope.onMenuTreeSelect = function(node) {
						if(node.url) {
							var pageObj = {};
							angular.copy(node,pageObj);
							scope.currentPage = pageObj;
						} else {
							scope.menuTree.toggle(node);
						}
					};
					scope.onNavTabSelect = function(page) {
						scope.currentPage = page;
						//直接映射页面
						$location.path(page.url);
						$location.replace();
						
						ZFrame.eachTree(scope.menuData,function(node) {
							if(scope.menuMap[node.url]&&node.url == page.url) {
								scope.menuTree.toggle(node);
							}
						});
					};
					scope.navModel = ZModel.getInstance().navModel;
					$timeout(function() {
						scope.$watch('navModel.location',function(location) {
							if(location&&location.page) {
//								if(location.page=="index") {
//									return;
//								}
								if(scope.currentPage&&scope.currentPage.url == location.page) return;
								var pageObj = {};
								//找到就打开页面，找不到进行相应处理，404或index
								if(scope.menuMap[location.page]) {
									pageObj.title = scope.menuMap[location.page].label;
									pageObj.url = location.page;
								} else {
									//进行alert 提示当前页面不存在
									$location.path("/index");
									$location.hash("");
									$location.replace();
									return;
								}
								if(location.params) {//url传递对象解析
									var dataObj = {};
									var params = location.params.split("/");
									for(var i = o;i<params.length;i++) {
										var map = params[i].splite("=");
										if(map.length==2) {
											dataObj[map[0]] = map[1];
										}
									}
									pageObj.data = dataObj;
								}
								scope.currentPage = pageObj;
							}
						});
					});
				});
			};
			
			//scope.bindMenuData();
			scope.bindTokenData();
		} ]);

//用户管理控制器
app.controller("z-user-grid-c",['$scope','ZModel', 'z-user-s',function(scope,ZModel,UserService){
	scope.userModel = ZModel.getInstance().userModel;
	scope.editModel = {};
	scope.viewModel = {};
	scope.viewModel.users = [];
	scope.editModel.editUser = {};
	scope.editModel.editTitle = "";
	scope.editModel.editType = "";
	scope.userModel.users = [];
	//数据绑定
	scope.bindUserData = function(){
		UserService.getUserData(function(data){
				scope.viewModel.users = data;
		});
	};
	scope.bindUserData();

	//scope.viewModel.users = [{accountId:"1",name:"1",password:"1",phone:"1",createTime:"2014-11-24 12:18:53",updateTime:null,roleName:null,depName:null},{accountId:"2",name:"2",password:"2",phone:"2",createTime:"2014-11-24 09:55:10",updateTime:null,roleName:null,depName:null}];

	//删除用户
	scope.viewModel.delUser = function(id){
		UserService.deleteUser(id,function(){
			scope.bindUserData();
		});
	};
	scope.viewModel.editUser = function(user){
		scope.editModel.editUser = user;
		scope.editModel.editTitle = "编辑用户";
		scope.editModel.editType = "edit";
	};
	scope.viewModel.addUser = function(){
		scope.editModel.editUser = {};
		scope.editModel.editTitle = "新增用户";
		scope.editModel.editType = "add";
	};
	scope.editModel.saveUser = function(type){
		if(type=="edit"){
			UserService.saveUser(scope.editModel.editUser,function(){
				scope.bindUserData();
				scope.editModel.editUser = {};
			});
		}
		if(type=="add"){
			UserService.addUser(scope.editModel.editUser,function(){
				scope.bindUserData();
				scope.userModel.editUser = {};
			});
		}
	};
	
}]);

app.controller("z-menu-tree-c", [
		'$scope',
		'ZModel',
		'z-edit-menu-s',
		function(scope, ZModel, EditMenuService) {
			scope.viewModel = {};
			scope.viewModel.treeData = [];
			scope.viewModel.currentNode = {};//当前选择的节点
			scope.viewModel.tree = {};
			scope.viewModel.onSelect = function(node) {
				debugger;
				scope.viewModel.currentNode = node;
				scope.viewModel.tree.toggle(node);
			};
			scope.viewModel.toggle = function(node) {
				scope.viewModel.tree.toggle(node);
			};
			scope.editModel = {};
			scope.editModel.treeList = [];
			scope.editModel.editBtnHide = false;
			scope.editModel.windowTitle = "";
			scope.editModel.tempNode = {};
			//编辑窗口的选择上级菜单下拉默认值
			scope.editModel.selTreeListItem = {};
			scope.viewModel.bindTreeData = function() {
				EditMenuService.getMenuData(function(data) {
						scope.viewModel.treeData = formatCheckboxVal(data);
				});
			};
			
			function formatCheckboxVal(menuData){
				var newData = [];
				if(menuData) {
					for(var i = 0 ;i<menuData.length;i++){
						var node = {};
						node.id = menuData[i].id;
						node.pId = menuData[i].pId;
						node.isMainPage = menuData[i].isMainPage==undefined?false:menuData[i].isMainPage;
						node.alias = menuData[i].alias;
						node.url = menuData[i].url;
						node.code = menuData[i].code;
						node.label = menuData[i].label;
						node.children = formatCheckboxVal(menuData[i].children);
						newData.push(node);
					}
				}
				return newData;
			}
			
			//添加菜单
			scope.viewModel.addMenu = function() {
				scope.editModel.windowTitle = "新增菜单";
				scope.editModel.type = "add";
				scope.editModel.treeList = getOtherNodeList(scope.viewModel.treeData);
				scope.editModel.selTreeListItem = "";
			};
			//删除菜单
			scope.viewModel.delMenu = function() {
				var currentNode = scope.viewModel.currentNode;
				scope.viewModel.tree.del_branch(currentNode);
				scope.saveMenu();
			};
			//编辑菜单
			scope.viewModel.editMenu = function() {
				scope.editModel.windowTitle = "编辑菜单";
				scope.editModel.type = "edit";
				angular.copy(scope.viewModel.currentNode,scope.editModel.tempNode);
				scope.editModel.treeList = getOtherNodeList(scope.viewModel.treeData,scope.viewModel.currentNode);
				scope.editModel.selTreeListItem = scope.viewModel.tree.get_parent_branch(scope.viewModel.currentNode);
			};
			//保存修改
			scope.editModel.saveChange = function(){
				var parentNode = scope.editModel.selTreeListItem;
				
				var cloneNode = {};
				angular.copy(scope.editModel.tempNode,cloneNode);
				if(scope.editModel.type == "add"){//新增时保存方法
					//cloneNode.isMainPage = scope.editModel.tempNode.isMainPage?1:0;
					if(parentNode){
						scope.viewModel.tree.add_branch(parentNode,cloneNode);
					}else{
						scope.viewModel.tree.add_root_branch(cloneNode);
					}
				}else{//编辑时保存方法
					var currentNode = scope.viewModel.currentNode;
					scope.viewModel.tree.del_branch(currentNode);
					currentNode.id = scope.editModel.tempNode.id;
					currentNode.pId = scope.editModel.tempNode.pId;
					currentNode.label = scope.editModel.tempNode.label;
					currentNode.url = scope.editModel.tempNode.url;
					currentNode.code = scope.editModel.tempNode.code;
					currentNode.alias = scope.editModel.tempNode.alias;
					currentNode.isMainPage = scope.editModel.tempNode.isMainPage;
					if(parentNode){
						scope.viewModel.tree.add_branch(parentNode,currentNode);
					}else{
						scope.viewModel.tree.add_root_branch(currentNode);
					}
				}
				
				scope.saveMenu();
			};
			//保存菜单
			scope.saveMenu = function(){
				var newData = replaceData(scope.viewModel.treeData);
				
				EditMenuService.saveMenuList(newData,function(){
					alert("保存成功");
//					scope.viewModel.bindTreeData();
				});
			};

			//获取除这棵树意外的其他节点的List
			var getOtherNodeList = function(menuData,node){
				var result = [];
				if(menuData) {
					for(var i = 0;i<menuData.length;i++){
						if(!node||menuData[i].id.toString()!=node.id.toString()){
							if(!menuData[i].url||menuData[i].url=="") {
								result.push(menuData[i]);
								var temp = getOtherNodeList(menuData[i].children,node);
								for(var j = 0;j<temp.length;j++ ){
									result.push(temp[j]);
								}
							}
						}
					}
				}
				return result;
			};
			//按照格式替换新的按钮Data
			replaceBtnData = function(btnData){
				var newData = [];
				if(btnData) {
					for(var i = 0 ;i<btnData.length;i++){
						if(btnData[i].code&&btnData[i]!=""){
							var btn = {};
							btn.code = btnData[i].code;
							btn.name = btnData[i].name;
							newData.push(btn);
						}
					}
				}
				return newData;
			};
			//按照格式替换新的Data
			replaceData = function(menuData){
				var newData = [];
				if(menuData) {
					for(var i = 0 ;i<menuData.length;i++){
						var node = {};
						node.id = menuData[i].id;
						node.pId = menuData[i].pId;
						node.isMainPage = menuData[i].isMainPage;
						node.alias = menuData[i].alias;
						node.url = menuData[i].url;
						node.code = menuData[i].code;
						node.label = menuData[i].label;
						node.children = replaceData(menuData[i].children);
						newData.push(node);
					}
				}
				return newData;
			};
			
			scope.viewModel.bindTreeData();
			
			/*
			 * //菜单数据源 scope.viewModel.treeData = [ { label: '菜单1', children: [ { id:1,
			 * label: '菜单11', url:'html/user/indexXXX.html' }, { id:4, label:
			 * '菜单12', url:'html/menu/menuManage.html' } ] }, { label: '菜单2',
			 * children: [ { id:2, label: '菜单21', url:'html/home/welcome.html' }, {
			 * id:3, label: '菜单22', url:'html/menu/menuManage.html' } ] } ];
			 */
		} ]);
/**
 * Created by LiYunpeng on 11/25/14.
 */
//菜单管理控制器
app.controller("z-role-tree-c", [
	'$scope',
	'ZModel',
	'z-role-s',
	function(scope, ZModel, RoleService) {
		scope.viewModel = {};
		scope.viewModel.treeData = [];//树形数据源
		scope.viewModel.currentNode = {};//当前选择的节点
		scope.viewModel.tree = {};
		scope.viewModel.onSelect = function(node) {
			scope.viewModel.currentNode = node;
			scope.viewModel.tree.toggle(node);
		};
		scope.viewModel.toggle = function(node) {
			scope.viewModel.tree.toggle(node);
		};
		scope.editModel = {};
		scope.editModel.treeList = [];//树形转化为的一维数组
		scope.editModel.selTreeListItem = {};
		scope.editModel.windowTitle = "";
		scope.editModel.tempNode = {};//临时数据源，用于编辑页使用
		//绑定数据源
		scope.viewModel.bindTreeData = function() {
			RoleService.getRoleData(function(data) {
					scope.viewModel.treeData = data;
			});
		};
		//添加角色
		scope.viewModel.addRole = function() {
			scope.editModel.windowTitle = "新增菜单";
			scope.editModel.type = "add";
			scope.editModel.tempNode = {};
			scope.editModel.tempNode.id = ZFrame.getUUID();
			scope.editModel.treeList = getOtherNodeList(scope.viewModel.treeData);
			scope.editModel.selTreeListItem = "";
		};
		//删除角色
		scope.viewModel.delRole = function() {
			var currentNode = scope.viewModel.currentNode;
			scope.viewModel.tree.del_branch(currentNode);
			scope.saveRole();
		};
		//编辑角色
		scope.viewModel.editRole = function(event) {
			scope.editModel.windowTitle = "编辑菜单";
			scope.editModel.type = "edit";
			angular.copy(scope.viewModel.currentNode,scope.editModel.tempNode);
			//scope.editModel.treeList = getOtherNodeList(scope.viewModel.treeData);
			scope.editModel.treeList = getOtherNodeList(scope.viewModel.treeData,scope.viewModel.currentNode);
			scope.editModel.selTreeListItem = scope.viewModel.tree.get_parent_branch(scope.viewModel.currentNode);
		};
		//保存修改到缓存数据
		scope.editModel.saveChange = function(){
			var parentNode = scope.editModel.selTreeListItem;
			var cloneNode = {};
			angular.copy(scope.editModel.tempNode,cloneNode);
			
			if(scope.editModel.type == "add"){//新增时保存方法
				if(parentNode){
					scope.viewModel.tree.add_branch(parentNode,cloneNode);
				}else{
					scope.viewModel.tree.add_root_branch(cloneNode);
				}
			}else{//编辑时保存方法
				var currentNode = scope.viewModel.currentNode;

				
//				currentNode.url = scope.editModel.tempNode.url;
//				currentNode.code = scope.editModel.tempNode.code;

				scope.viewModel.tree.del_branch(currentNode);
				currentNode.label = scope.editModel.tempNode.label;

				if(parentNode){
					scope.viewModel.tree.add_branch(parentNode,currentNode);
				}else{
					scope.viewModel.tree.add_root_branch(currentNode);
				}
			}
			
			scope.saveRole();
		};
		//保存菜单
		scope.saveRole = function(){
			var newData = replaceData(scope.viewModel.treeData);
			RoleService.setRoleDate(newData,function(){
				//scope.viewModel.bindTreeData();
				console.log("保存角色成功");
			});
		};
		//将菜单转换为一维数组（除自己及自己的子孙节点外）
		var getOtherNodeList = function(treeData,node){
			var result = [];
			if(treeData) {
				for(var i = 0;i<treeData.length;i++){
					if(!node||treeData[i].id.toString()!=node.id.toString()){
						result.push(treeData[i]);
						var temp = getOtherNodeList(treeData[i].children,node);
						for(var j = 0;j<temp.length;j++ ){
							result.push(temp[j]);
						}
					}
				}
			}
			return result;
		};
		//按照格式替换新的Data
		replaceData = function(treeData){
			var newData = [];
			if(treeData) {
				for(var i = 0 ;i<treeData.length;i++){
					var node = {};
					node.id = treeData[i].id;
					node.label = treeData[i].label;
					node.children = replaceData(treeData[i].children);
					newData.push(node);
				}
			}
			return newData;
		};

		scope.viewModel.bindTreeData();
		
	} ]);

//角色权限管理
app.controller("z-permission-tree-c", [ '$scope', 'ZModel', 'z-permission-s','$rootScope',
		function(scope, ZModel, PermissionService,$rootScope) {
			scope.roleModel = {};
			scope.roleModel.menuData = [];
			scope.roleModel.tree = {};
			scope.roleModel.editTitle="";
			scope.roleModel.currentNode =null;
			scope.roleModel.errorList=[];
			scope.permissionModel = {};
			scope.permissionModel.menuData = [];
			scope.permissionModel.tree = {};
			scope.roleModel.bindData = function(){
				scope.roleModel.isLoading=true;
				PermissionService.getPrivilegeGroupTree(function(data){
					scope.roleModel.menuData = data;
					scope.roleModel.isLoading=false;
				});
			};
			scope.permissionModel.getPrivilegeGroupMenuById = function(privilegeGroupId) {
				scope.roleModel.isLoading=true;
				PermissionService.getPrivilegeGroupMenuById(privilegeGroupId, function(data) {
					scope.permissionModel.privilegeGroupCode=data.privilegeGroupCode;
					scope.permissionModel.privilegeGroupName=data.privilegeGroupName;
					scope.permissionModel.menuData = data.menuDataBeanList;
					scope.roleModel.isLoading=false;
				},function(){
					scope.roleModel.isLoading=false;
				});
			};
			scope.roleModel.bindData();
			
			scope.roleModel.load=function(){
				scope.roleModel.show=true;
			};
			scope.roleModel.unLoad=function(){
				scope.roleModel.show=false;
				//scope.roleModel.currentNode =null;
				scope.permissionModel.privilegeGroupCode="";
				scope.permissionModel.privilegeGroupName="";
				scope.permissionModel.menuData = [];
				scope.canShowPrivilegeGroupNameError=false;
				scope.canShowPrivilegeGroupCodeError=false;
			};
			scope.roleModel.onSelect = function(node) {
				scope.roleModel.currentNode = node;
				scope.roleModel.tree.toggle(node);
			};
			scope.roleModel.toggle = function(node) {
				scope.roleModel.tree.toggle(node);
			};
			scope.permissionModel.onSelect = function(node) {
				//scope.roleModel.currentNode = node;
				scope.permissionModel.tree.toggle(node);
			};
			scope.permissionModel.toggle = function(node) {
				scope.permissionModel.tree.toggle(node);
			};
			/*scope.roleModel.tree.onSelect = function(node){
				scope.roleModel.currentNode = node;
			};*/
			scope.permissionModel.expend = function() {
				scope.permissionModel.tree.expand_all();
			};
			
			scope.roleModel.addPermission=function(){
				scope.roleModel.editTitle="新增";
				scope.roleModel.type = "add";
				scope.roleModel.load();
				scope.roleModel.currentNode={};
				scope.roleModel.currentNode.id="";
				PermissionService.getPrivilegeGroupMenuById(null, function(data) {
					scope.permissionModel.menuData = data.menuDataBeanList;
				});
			};
			
			scope.roleModel.editPermission = function(){
				if(scope.roleModel.currentNode!=null){
					scope.roleModel.editTitle="编辑";
					scope.roleModel.type = "edit";
					scope.roleModel.load();
					scope.permissionModel.getPrivilegeGroupMenuById(scope.roleModel.currentNode.id);
				}else{
					$rootScope.alertWarning("请选择权限组。");
				}
			};
			//删除
			scope.roleModel.deletePermission=function(){
				if(scope.roleModel.currentNode!=null){
					if(scope.roleModel.currentNode.id==1){
						$rootScope.alertWarning("系统管理员权限不能删除。");
						return;
					}
					$rootScope.alertConfirm("确定删除权限组吗？",function() {
						PermissionService.deletePrivilegeGroupMenu(scope.roleModel.currentNode.id, 
						function() {
							$rootScope.alertInfo("删除权限组成功。");
							scope.roleModel.bindData();
						},function(error){
							$rootScope.alertError(error.fault.message);
						});
					});
				}else{
					$rootScope.alertWarning("请选择权限组。");
				}
			};
			//保存
			scope.permissionModel.save = function() {
				var result = [];
				replaceData(result, scope.permissionModel.menuData);
				var permissionList ={};
				permissionList.privilegeGroupId=scope.roleModel.currentNode.id;
				permissionList.privilegeGroupCode=scope.permissionModel.privilegeGroupCode;
				permissionList.privilegeGroupName=scope.permissionModel.privilegeGroupName;
				permissionList.menuDataBeanList=result;
				
				if(scope.roleModel.type =="add"){
					PermissionService.addPrivilegeGroupMenu(permissionList,function(data){
						$rootScope.alertInfo("保存权限组成功。");
						scope.roleModel.bindData();
						scope.roleModel.unLoad();
					},function(error){
						$rootScope.alertError(error.fault.message);
					});
				}else{
					PermissionService.updatePrivilegeGroupMenu(permissionList,function(data){
						$rootScope.alertInfo("修改权限组成功。");
						scope.roleModel.bindData();
						scope.roleModel.unLoad();
					},function(error){
						$rootScope.alertError(error.fault.message);
					});
				}
			};
			
			//全局校验
			scope.roleModel.saveCheckGlobal = function(){
				for(var i=0;i<scope.roleModel.errorList.length;i++){
					if(scope.roleModel.errorList[i].error){
						return true;
					}
				}
				return false;
			};
			
			scope.roleModel.checkRequiredRange = function($error,$ngModel,errorName){
				var index = -1;
				for(var i=0;i<scope.roleModel.errorList.length;i++){
					if(scope.roleModel.errorList[i].name == errorName){
						index = i;
						scope.roleModel.errorList[i].error = false;
					}
				}
				
				if($error){
					if($error.required) {
						if(index == -1){
							scope.roleModel.errorList.push({name:errorName,error:true});
						}else{
							scope.roleModel.errorList[index].error = true;
						}
						return '不能为空';
					}
				}
				return '';
			};

			//按照格式替换新的Data
			replaceData = function(newData, oldData) {
				for ( var i = 0; i < oldData.length; i++) {
					var node = {};
					node.code = oldData[i].code;
					node.label = oldData[i].label;
					node.checked = oldData[i].checked;
					node.type = oldData[i].type;
					node.children = [];
					replaceData(node.children, oldData[i].children);
					newData.push(node);
				}
			};
		} ]);

app.controller("z-logout-c",[ '$scope','$rootScope','$location',"z-logout-s","z-password-s",'z-SessionTimer-s','$interval',
                              function(scope,$rootScope,$location,LogoutService,PasswordService,SessionTimer,$interval) {
	scope.changePassObj = {};
	scope.oldPassRight = "";
	scope.tipType=false;
	//scope.tipType=true;
	scope.tipData={}; 
	scope.tipData.total=0;
	
	var time =null;
	
	//定义全局函数
	$rootScope.rootTotal=function(){
		scope.getTips();
	};
	
	scope.getTips=function(){
		//scope.tipData.total=scope.tipData.total+1;
		//查询是否为待审批
		LogoutService.getPrivilegeGroupIdType(function(data) {
			scope.tipType=data;
			if(scope.tipType){
				 //time =$interval(function(){  
					LogoutService.getTips(function(data) {
						scope.tipData=data;
					},function(error) {
//						$interval.cancel(time);  
//						time=null;
					});
	            //},3000);
			}
		},function() {});
	};
	scope.getTips();

	scope.Login=function(){
		$location.path("/login");
		$location.hash("");
		$location.replace();
		$rootScope.currentUser = null;
	};
	
	scope.showChangePassWindow = function() {
		scope.changePassObj = {};
	};
	scope.validPass = function(bool) {
		if(bool) {
			return '输入的新密码不一致';
		} else {
			return '';
		}
	};
	scope.validOldPass = function(){
		scope.oldPassRight="";
	};
	scope.changePassword = function() {
		scope.isLoading = true;
		var check = /^(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*[^\sA-Za-z0-9])\S{8,}$/;
		if(scope.changePassObj.oldPassword == "" || scope.changePassObj.oldPassword == undefined){
			$rootScope.alertWarning("旧密码不能为空！");
			scope.isLoading = false;
		}else if(scope.changePassObj.newPassword == "" || scope.changePassObj.newPassword == undefined){
			$rootScope.alertWarning("新密码不能为空！");
			scope.isLoading = false;
		}else if(scope.changePassObj.confirmPassword == "" || scope.changePassObj.confirmPassword == undefined){
			$rootScope.alertWarning("请再次输入密码！");
			scope.isLoading = false;
		}else if(scope.changePassObj.confirmPassword != scope.changePassObj.newPassword){
			$rootScope.alertWarning("两次输入的新密码不一致！");
			scope.isLoading = false;
		}else if(!check.test(scope.changePassObj.newPassword) || !check.test(scope.changePassObj.confirmPassword)){
			$rootScope.alertWarning("密码格式不正确(须含有大小写字母，数字，特殊符号，长度为8位及8位以上)！");
			scope.isLoading = false;
		}else{
			PasswordService.changePassword(scope.changePassObj,function() {
				scope.isLoading = false;
				localStorage.setItem('password','');
				$('#passwordEditWindow').modal('hide');
				$rootScope.alertConfirm("密码已修改成功，是否重新登录",function() {
					$location.path("/login");
					$location.hash("");
					$location.replace();
					$rootScope.currentUser = null;
				},function() {
					$('#passwordEditWindow').modal('hide');
				});
			},function(error) {
				scope.isLoading = false;
				scope.oldPassRight = "原密码不正确";
				$rootScope.alertError(error.fault.message);
//				$rootScope.alertError("原密码不正确",function() {
////					$('#passwordEditWindow').modal('hide');
//				});
			});
		}
	};
	
	scope.logout = function() {
		$rootScope.alertConfirm("确定注销？",function() {
			//scope.isLoading = true;
			LogoutService.logout(function() {
				//scope.isLoading = false;
				$location.path("/login");
				$location.hash("");
				$location.replace();
				$rootScope.currentUser = null;
				SessionTimer.unlistenTimeout();
			},function() {
				//scope.isLoading = false;
				$location.path("/login");
				$location.hash("");
				$location.replace();
				$rootScope.currentUser = null;
			});
		});
	};
}]);

//忘记密码
app.controller("z-forgetPassword-c", [ '$scope','$rootScope', '$location','z-user-s','z-forgetPassword-s',
	function(scope,$rootScope, $location,UserService,forgetPasswordService) {
		scope.loginModel = {};
		scope.loginModel.loginName = localStorage.getItem('loginName');
		scope.loginModel.password = localStorage.getItem('password');
		scope.loginModel.alertDangerText = "";
		scope.loginModel.alertDangerPassText="";
		scope.loginModel.mail="";
		scope.loginModel.CSRFToken="";
		scope.loginModel.hideAlert = true;
		scope.loginModel.passwordType=false;
		scope.loginModel.logonType= true;
		scope.loginModel.hideAlertPass=true;
		scope.loginModel.forgetType=false;
		//链接link更改密码 TODO
		scope.loginModel.saveOn= function() {
		var check = /^(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*[^\sA-Za-z0-9])\S{8,}$/;
		if(scope.loginModel.newPassword == "" || scope.loginModel.newPassword == undefined){
			$rootScope.alertWarning("新密码不能为空！");
		}else if(scope.loginModel.confirmPassword == "" || scope.loginModel.confirmPassword == undefined){
			$rootScope.alertWarning("请再次输入密码！");
		}else if(scope.loginModel.confirmPassword != scope.loginModel.newPassword){
			$rootScope.alertWarning("两次输入的新密码不一致！");
		}else if(!check.test(scope.loginModel.newPassword) || !check.test(scope.loginModel.confirmPassword)){
			$rootScope.alertWarning("密码格式不正确(须含有大小写字母，数字，特殊符号，长度为8位及8位以上)！");
		}else{
			var search=$location.search()['key'];
			//验证是否存在key
			if(angular.isUndefined(search)){
				//不存在
				//currentUser();
				$rootScope.alertWarning("无效的链接地址！");
			}else{
				
			}
			scope.changePassObj={};
			scope.changePassObj.loginName=scope.loginModel.loginName;
			scope.changePassObj.newPassword=scope.loginModel.newPassword;
			scope.isLoading = true;
			forgetPasswordService.doResetPassword({
				key:search,
				pw1:scope.loginModel.newPassword,
				pw2:scope.loginModel.confirmPassword
			},function() {
				scope.isLoading = false;
				$rootScope.alertConfirm("密码已修改成功，是否重新登录",function() {
					$location.path("/login");
					$location.search("")
					$location.hash("");
					$location.replace();
					$rootScope.currentUser = null;
				},function() {
					$('#passwordEditWindow').modal('hide');
				});
			},function(error) {
				scope.isLoading = false;
				scope.loginModel.hideAlertPass=false;
				scope.loginModel.alertDangerPassText = error.message;
//				$rootScope.alertError(error.fault.message);
			});
		}
	};
}]);


//登录管理
app.controller("z-login-c", [ '$scope','$rootScope', '$location', 'z-login-s','z-init-s','z-SessionTimer-s','$z-http','ZModel',"z-password-s","tokenService","Md5",
		function(scope,$rootScope, $location, LoginService,InitService,SessionTimer,$zhttp,ZModel,PasswordService,tokenService,Md5) {
	
			scope.loginModel = {};
//			scope.loginModel.loginName = "";
//			scope.loginModel.password = "";
			scope.loginModel.remberPassword = localStorage.getItem('remberPassword');
			if(scope.loginModel.remberPassword == "true"){
				scope.loginModel.remberPassword = true;
			}else{
				scope.loginModel.remberPassword = false;
			}
			scope.loginModel.loginName = localStorage.getItem('loginName');
			scope.loginModel.password = localStorage.getItem('password');
			scope.loginModel.alertDangerText = "";
			scope.loginModel.alertDangerPassText="";
			scope.loginModel.mail="";
			scope.loginModel.CSRFToken="";
			scope.loginModel.hideAlert = true;
			scope.loginModel.passwordType=false;
			scope.loginModel.logonType= true;
			scope.loginModel.hideAlertPass=true;
			scope.loginModel.forgetType=false;
			
			//验证
			scope.loginModel.requiredForm= function() {
	            if (!scope.loginForm.$valid) {
	           /* 	if(!scope.loginForm.name.$dirty){
	            		scope.loginForm.name.$dirty=true;
	            	}
	            	if(!scope.loginForm.pw.$dirty){
	            		scope.loginForm.pw.$dirty=true;
	            	}*/
	                return true;
	            }else{
	                return false;
	            }
	        };
	        
	        /**
	         * 初始化
	         */
	        scope.loginModel.init=function(){
	        	//加载用户登录身份认证编号
	        	LoginService.getCSRFToken(function(data) {
	        				scope.loginModel.CSRFToken=data;
						}, function(data) {});
	        };
	        scope.loginModel.init();

	        /**
	         * 登录
	         */
	    /*	$(document).keyup(function(event){
	      		if(event.keyCode ==13){
		  				  scope.loginModel.login();
		  		  }
	      	});*/
	      	
			scope.loginModel.login = function() {
				if(scope.loginModel.requiredForm()){
					return;
				}
				scope.isLoading = true;
				//验证登陆账号密码是否更改
				LoginService.getVerificationPassword(
						scope.loginModel.loginName,
						scope.loginModel.password, 
						scope.loginModel.CSRFToken,
						function(data) {
							scope.isLoading = false;
							scope.loginModel.passwordType=data;
							if(scope.loginModel.passwordType==false){
								scope.loginModel.loginGo();
							}else{
								scope.loginModel.logonType= false;
							}
						}, function(data) {
							scope.isLoading = false;
							scope.loginModel.alertDangerText = data.message;
							scope.loginModel.loginName = "";
							scope.loginModel.hideAlert = false;
						});
			};
			
			//回车登录
			scope.loginModel.myKeyup = function(e){
			 		//IE 编码包含在window.event.keyCode中，Firefox或Safari 包含在event.which中
					var keycode = window.event?e.keyCode:e.which; 
			        if(keycode==13){
			        		scope.loginModel.login();
			        }
			};
			
			//忘记密码
			scope.loginModel.forget= function() {
				scope.loginModel.forgetType=true;
				scope.loginModel.logonType= false;
			};
			
			//返回
			scope.loginModel.forgetReturn= function() {
				scope.loginModel.forgetType=false;
				scope.loginModel.logonType= true;
			};
			
			//发送邮箱
			scope.loginModel.sendMail= function() {
				if(scope.loginModel.mail== "" || scope.loginModel.mail == undefined){
					$rootScope.alertWarning("邮箱不能为空！");
				}else{
					scope.isLoading = true;
					//验证邮箱存在后发生邮箱
					LoginService.forgetPassword(scope.loginModel.CSRFToken,
							{mail:scope.loginModel.mail},function(data) {
								$rootScope.alertInfo("邮件发送成功。");	
								scope.isLoading = false;
								scope.loginModel.forgetType=false;
								scope.loginModel.logonType= true;
							}, function(data) {
								scope.isLoading = false;
								$rootScope.alertWarning(data.message);
							});
				}
			};
			
			
			//保存更改密码
			scope.loginModel.saveOn= function() {
				var check = /^(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*[^\sA-Za-z0-9])\S{8,}$/;
				if(scope.loginModel.oldPassword == "" || scope.loginModel.oldPassword == undefined){
					$rootScope.alertWarning("旧密码不能为空！");
				}else if(scope.loginModel.newPassword == "" || scope.loginModel.newPassword == undefined){
					$rootScope.alertWarning("新密码不能为空！");
				}else if(scope.loginModel.confirmPassword == "" || scope.loginModel.confirmPassword == undefined){
					$rootScope.alertWarning("请再次输入密码！");
				}else if(scope.loginModel.confirmPassword != scope.loginModel.newPassword){
					$rootScope.alertWarning("两次输入的新密码不一致！");
				}else if(!check.test(scope.loginModel.newPassword) || !check.test(scope.loginModel.confirmPassword)){
					$rootScope.alertWarning("密码格式不正确(须含有大小写字母，数字，特殊符号，长度为8位及8位以上)！");
				}else{
					scope.changePassObj={};
					scope.changePassObj.loginName=scope.loginModel.loginName;
					scope.changePassObj.oldPassword=scope.loginModel.oldPassword;
					scope.changePassObj.newPassword=scope.loginModel.newPassword;
					scope.isLoading = true;
					PasswordService.changePassword(scope.changePassObj,function() {
						scope.isLoading = false;
						$rootScope.alertConfirm("密码已修改成功，是否重新登录",function() {
							scope.loginModel.hideAlertPass=true;
							scope.loginModel.alertDangerPassText = "";
							scope.loginModel.passwordType=false;
							scope.loginModel.logonType= true;
						},function() {
							
						});
					},function(error) {
						scope.isLoading = false;
						scope.loginModel.oldPassword="";
						scope.loginModel.hideAlertPass=false;
						scope.loginModel.alertDangerPassText = error.message;
					});
				}
			};
			
			scope.$watch('loginModel.loginName',function(newValue,oldValue) {
				if(newValue!=""){
					scope.loginModel.hideAlert = true;
				}
			});
			
			scope.$watch('loginModel.password',function(newValue,oldValue) {
				if(newValue!=""){
					scope.loginModel.hideAlert = true;
				}
			});
			
			//登陆跳转
			scope.loginModel.loginGo = function() {
				/*Md5.hex_md5(scope.loginModel.password)*/
				LoginService.login(
						scope.loginModel.loginName,
						scope.loginModel.password, 
						scope.loginModel.CSRFToken,
						function(data) {
							//设置全局变量
							tokenService(data.token, true); 
							if(scope.loginModel.remberPassword){
								localStorage.setItem('loginName',scope.loginModel.loginName);
								localStorage.setItem('password',scope.loginModel.password);
								localStorage.setItem('remberPassword','true');
							}else{
								localStorage.removeItem('loginName');
								localStorage.removeItem('password');
								localStorage.removeItem('remberPassword');
							}
							//执行初始化服务
							InitService.init(function(data) {
								SessionTimer.listenTimeout(function() {$zhttp.post('session/checkTimeout.do');},data,function() {
									//alert("提示会话超时，任何操作查询及保存将无效，询问是否重新登陆，是则调回登录页，否则无任何操作关闭提示");
									
//									$rootScope.alertConfirm("会话已超时，任何操作查询及保存将无效，是否重新登录?",function() {
//										//记录作为要访问的页面，并跳转到登陆页
//										$rootScope.currentUser = null;
//										ZModel.getInstance().navModel.beforeLoginUrl = $location.$$url;
//										
//										$location.path("/login");
//										$location.hash("");
//										$location.replace();
//									},function() {
//										SessionTimer.listenTimeout();
//									});
									
									/*var _confirm = window.confirm("会话已超时，任何操作查询及保存将无效，是否重新登录?");
									if(_confirm){*/
											//记录作为要访问的页面，并跳转到登陆页
											$rootScope.currentUser = null;
											ZModel.getInstance().navModel.beforeLoginUrl = $location.$$url;
											
											$location.path("/login");
											$location.hash("");
											$location.replace();
									/*} else {
										SessionTimer.listenTimeout();
									}*/
								});
								$location.path("/index");
								$location.hash("");
								$location.replace();
							});
						}, function(data) {
								scope.loginModel.alertDangerText = data.message;
								scope.loginModel.password = "";
								scope.loginModel.hideAlert = false;
						});
			};
}]);

app.controller('z-404-c', [ '$scope', '$location', function($scope, $location) {
	$scope.homePage = function() {
		$location.path('/index');
		$location.hash('');
		$location.replace();
	}
}]);